/*
============================================================================
 Name        : PlayerPlugin.cpp
 Author      : 
 Version     :
 Copyright   : Your copyright notice
 Description : CPlayerPlugin implementation
============================================================================
*/

#include "PlayerPlugin.h"

#include <eikmenup.h>
#include <caknfileselectiondialog.h>
#include <MdaAudioSamplePlayer.h>

#include "PluginUtility.h"
#include "Id3v1Tag.h"

#include "fileplayer.mbg"	//Enum Embm...

#define BITMAP_PLAY			(TInt)EMbmFileplayerPlay
#define BITMAP_PLAY_MASK	(TInt)EMbmFileplayerPlay_mask
#define BITMAP_PAUSE		(TInt)EMbmFileplayerPause
#define BITMAP_PAUSE_MASK	(TInt)EMbmFileplayerPause_mask
#define BITMAP_STOP			(TInt)EMbmFileplayerStop
#define BITMAP_STOP_MASK	(TInt)EMbmFileplayerStop_mask
#define BITMAP_ERROR		(TInt)EMbmFileplayerError
#define BITMAP_ERROR_MASK	(TInt)EMbmFileplayerError_mask

_LIT(KPlayerPluginMenuText, "File Player");
_LIT(KFilePlayerMbmFileName, "fileplayer.mbm");
_LIT(KMetadataSeparator, " - ");

enum TPlayerPluginCommandId
{
	EPluginCommandId = 0x6000,
	EOpenFileCommandId
};

CPlayerPlugin::CPlayerPlugin()
: iState(EStateNotReady), iVolume(0), iVolumeFactor(0)
{
}

CPlayerPlugin::~CPlayerPlugin()
{
	//Delete bitmaps
	iBitmaps.ResetAndDestroy();

	if (iState == EStatePlaying )
	{
		//Stop before exiting
		iMdaAudioPlayerUtility->Stop();
	}

	//Delete player
	DELETE(iMdaAudioPlayerUtility);
}

CPlayerPlugin* CPlayerPlugin::NewLC()
{
	CPlayerPlugin* self = new (ELeave)CPlayerPlugin();
	CleanupStack::PushL(self);
	self->ConstructL();
	return self;
}

CPlayerPlugin* CPlayerPlugin::NewL()
{
	CPlayerPlugin* self=CPlayerPlugin::NewLC();
	CleanupStack::Pop(); // self;
	return self;
}

void CPlayerPlugin::ConstructL()
{
	//Load bitmaps
	iBitmaps.Append(CPluginUtility::CreateBitmapL(KFilePlayerMbmFileName, BITMAP_PLAY));
	iBitmaps.Append(CPluginUtility::CreateBitmapL(KFilePlayerMbmFileName, BITMAP_PLAY_MASK));
	iBitmaps.Append(CPluginUtility::CreateBitmapL(KFilePlayerMbmFileName, BITMAP_PAUSE));
	iBitmaps.Append(CPluginUtility::CreateBitmapL(KFilePlayerMbmFileName, BITMAP_PAUSE_MASK));
	iBitmaps.Append(CPluginUtility::CreateBitmapL(KFilePlayerMbmFileName, BITMAP_STOP));
	iBitmaps.Append(CPluginUtility::CreateBitmapL(KFilePlayerMbmFileName, BITMAP_STOP_MASK));
	iBitmaps.Append(CPluginUtility::CreateBitmapL(KFilePlayerMbmFileName, BITMAP_ERROR));
	iBitmaps.Append(CPluginUtility::CreateBitmapL(KFilePlayerMbmFileName, BITMAP_ERROR_MASK));
}

const TDesC& CPlayerPlugin::GetMenuText()
{
	return KPlayerPluginMenuText;
}

TInt CPlayerPlugin::GetMenuCommand()
{
	return EPluginCommandId;
}

void CPlayerPlugin::AddExtraMenu(CEikMenuPane* aMenuPane)
{
	//Open file..
	CPluginUtility::AddMenuItem(EOpenFileCommandId, _L("Open file..."), aMenuPane);
}

void CPlayerPlugin::HandleCommandL(TInt aCommand)
{
	switch (aCommand)
	{
	case EOpenFileCommandId:
		OpenFileL();
		break;

	default:
		break;
	}
}

void CPlayerPlugin::Draw(CWindowGc& aGc, const TRect& /*aRect*/) const
{
}

void CPlayerPlugin::Activate()
{
	//Set metadata in ticker
	iContainer->SetTickerIcon((iMetadata.Length() > 0 ? iBitmaps[BITMAP_STOP] : NULL), iBitmaps[BITMAP_STOP_MASK]);
	iContainer->SetTickerText(iMetadata);
}

void CPlayerPlugin::Deactivate()
{
	//Stop playing
	if (IsReadyToStop()) StopL();
}

void CPlayerPlugin::PlayL()
{
	if (iState == EStateReadyToPlay || iState == EStatePaused )
	{
		//Set volume
		SetVolume(iVolume);

		//Set play icon
		iContainer->SetTickerIcon(iBitmaps[BITMAP_PLAY], iBitmaps[BITMAP_PLAY_MASK]);

		//Start playing
		iMdaAudioPlayerUtility->Play();
		iState = EStatePlaying;
	}
}

void CPlayerPlugin::PauseL()
{
	if (iState != EStatePlaying ) return;

	//Set pause icon
	iContainer->SetTickerIcon(iBitmaps[BITMAP_PAUSE], iBitmaps[BITMAP_PAUSE_MASK]);

	//Pause
	iMdaAudioPlayerUtility->Pause();
	iState = EStatePaused;
}

void CPlayerPlugin::StopL()
{
	if (iState == EStatePlaying || iState == EStatePaused )
	{
		//Set stop icon
		iContainer->SetTickerIcon(iBitmaps[BITMAP_STOP], iBitmaps[BITMAP_STOP_MASK]);

		//Stop
		iMdaAudioPlayerUtility->Stop();
		iState = EStateReadyToPlay;
	}
}

TBool CPlayerPlugin::IsReadyToPlay()
{
	return (iState == EStateReadyToPlay || iState == EStatePaused);
}

TBool CPlayerPlugin::IsReadyToPause()
{
	return (iState == EStatePlaying);
}

TBool CPlayerPlugin::IsReadyToStop()
{
	return (iState == EStatePlaying || iState == EStatePaused);
}

TInt CPlayerPlugin::Volume()
{
	if (!iMdaAudioPlayerUtility || iState == EStateNotReady) return 0;
	
	TInt volume;
	return iMdaAudioPlayerUtility->GetVolume(volume);
}

void CPlayerPlugin::SetVolume(TInt aVolume)
{
	iVolume = aVolume;
	if (!iMdaAudioPlayerUtility || iState == EStateNotReady) return;
	iMdaAudioPlayerUtility->SetVolume(iVolume * iVolumeFactor);
}

void CPlayerPlugin::OpenFileL()
{
	TFileName path;
	path = _L("C:\\");
	iFileName.Copy(_L("C:\\"));

	//Prompt for a file
	if (!CAknFileSelectionDialog::RunDlgLD(iFileName, path))
	{
		//Cancel
		iFileName.Zero();
		return;
	}

	//Open file
	OpenCurrentFileL();
}

void CPlayerPlugin::OpenCurrentFileL()
{
	//Create player
	DELETE(iMdaAudioPlayerUtility);
    iMdaAudioPlayerUtility = CMdaAudioPlayerUtility::NewFilePlayerL(iFileName, *this);

	//Show metadata
	ShowMetadataL();
}

void CPlayerPlugin::ShowMetadataL()
{
	TRAPD(err, {
		CId3v1Tag* tags = CId3v1Tag::NewLC(iFileName);
		
		iMetadata.Copy(tags->iTitle->Des());
		iMetadata.Append(KMetadataSeparator);
		iMetadata.Append(tags->iAlbum->Des());
		iMetadata.Append(KMetadataSeparator);
		iMetadata.Append(tags->iArtist->Des());

		//Set metadata in ticker
		iContainer->SetTickerText(iMetadata);

		CleanupStack::Pop();
		DELETE(tags);
	});

	if (err == KErrNone) return;

	//An error has occurred
	if (err == KErrNoMetada)
	{
		iContainer->SetTickerText(_L("No metadata available"));
	}
	else
	{
		//Error retrieving metadata
		iContainer->SetTickerText(_L("No metadata available"));
	}
}

// -----------------------------------------------------------------------------
// CPlayerAdapter::MapcInitComplete
// Call by the utility when playback initialization is completed.
// -----------------------------------------------------------------------------
//
void CPlayerPlugin::MapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds& /*aDuration*/ )
{
    iState = (aError ? EStateNotReady : EStateReadyToPlay);
    if (aError)
    {
		//An error has occurred
		iContainer->SetTickerIcon(iBitmaps[BITMAP_ERROR], iBitmaps[BITMAP_ERROR_MASK]);
		iContainer->SetTickerTextFormat(_L("Player initialization error: %d"), aError);
    }
    else
	{
		//Calculate volume factor in 10-scale
		iVolumeFactor = iMdaAudioPlayerUtility->MaxVolume() / 10;

		//Play
		PlayL();
	}
}

// -----------------------------------------------------------------------------
// CPlayerAdapter::MapcPlayComplete
// Call by the utility when playback has completed successfully or otherwise.
// -----------------------------------------------------------------------------
//

void CPlayerPlugin::MapcPlayComplete(TInt aError)
{
    iState = (aError ? EStateNotReady : EStateReadyToPlay);
    if ( aError )
    {
		//An error has occurred
		iContainer->SetTickerIcon(iBitmaps[BITMAP_ERROR], iBitmaps[BITMAP_ERROR_MASK]);
		iContainer->SetTickerTextFormat(_L("Error playing file: %d"), aError);
    }
}
